import React, { useEffect, useState } from 'react'
import useGetTableData from '@/hooks/useGetTableData'
import {
  getDisplayConfigList,
  importDisplayConfig,
  displayConfigExportExcel,
  updateDisplayConfig,
  getDisplayConfigUnConfigNum,
} from '@/api/reorder'
import { useForm } from 'antd/es/form/Form'
import PageContainer from '@/components/PageContainer'
import { useDisplayColumns } from '../columns'
import { ReorderDisplayConfigVO } from '../types'
import CustomTable from '@/components/CustomTable'
import { SearchForm } from '@/components/CustomForm'
import { IMPORT_FILE_ENUM, STATUSBANDOPTIONS, STATUSNUM } from '@/constant'
import { DownOutlined, ImportOutlined, PlusOutlined, UploadOutlined } from '@ant-design/icons'
import { useAppSelector } from '@/store/hooks'
import PermissionButton from '@/components/PermissionButton'
import './Display.less'
import useGetClassIds from '@/hooks/useGetClassIds'
import ImportFileModal from '@/components/ImportFileModal'
import { exportNotification, importNotification } from '@/utils/util'
import { useNavigate } from 'react-router-dom'
import { message, Typography } from 'antd'
const Index: React.FC = () => {
  const [hasKnowTop, sethasKnowTop] = useState(true)
  const [exportLoading, setexportLoading] = useState(false)
  const [isUploadFileShow, setisUploadFileShow] = useState<boolean>(false)
  const [unConfigInfo, setunConfigInfo] = useState(0)
  const [form] = useForm()
  const [FormUpload] = useForm()
  const [spinning, setspinning] = useState<boolean>(false)
  const navigate = useNavigate()
  const buttonCodeList = useAppSelector((state) => state.login.buttonCodeList) || []
  const { classIdOptions } = useGetClassIds()
  const [tableData, settableData] = useState<ReorderDisplayConfigVO[]>([])
  const { tableProps, params, setParams, search, reset } = useGetTableData<ReorderDisplayConfigVO>(
    getDisplayConfigList,
    {
      form: form,
      immediatelySend: false,
    },
  )
  useEffect(() => {
    settableData(tableProps.dataSource)
  }, [tableProps.dataSource])
  useEffect(() => {
    getNums()
    search({
      ...params,
    })
  }, [])
  const onUploadFileCancel = () => {
    FormUpload.resetFields()
    setisUploadFileShow(false)
  }
  const onUploadFileOk = async () => {
    const { file } = await FormUpload.validateFields()
    setexportLoading(true)
    const res = await importDisplayConfig<{ linkUrl: string }>(file).finally(() => {
      setexportLoading(false)
      FormUpload.resetFields()
    })
    if (res.code === 200) {
      importNotification(res?.data?.linkUrl)
      search(params)
      onUploadFileCancel()
    }
  }
  const onSave = async (info: ReorderDisplayConfigVO) => {
    const res = await updateDisplayConfig({ id: info.id, shopSkcDisplayQuantity: info.shopSkcDisplayQuantity }).finally(
      () => search(params),
    )
    if (res.code === 200) {
      message.success('操作成功')
    }
  }
  const getNums = async () => {
    const res = await getDisplayConfigUnConfigNum()
    if (res?.code === 200) {
      res?.data && setunConfigInfo(res.data)
    }
  }
  const reLoadPage = () => {
    search(params)
  }
  return (
    <PageContainer className="return_display_page">
      <div className="waittodo_box">
        <div className="wait_main">
          <div className="wm_item">
            <div className="wm_item_title">未维护基础陈列量</div>
            <div className="wm_item_num">
              <Typography.Link
                underline
                onClick={() => {
                  form.resetFields()
                  form.setFieldsValue({
                    shopSkcConfigFlag: 0,
                  })
                  search({
                    current: 1,
                    size: 10,
                    largeClassName: null,
                    midClassName: null,
                    smallClassName: null,
                    tinyClassName: null,
                    shopSkcConfigFlag: 0,
                  })
                }}
              >
                {unConfigInfo || 0}条
              </Typography.Link>
            </div>
          </div>
        </div>
      </div>
      <SearchForm
        className="reorder_display"
        params={params}
        form={form}
        searchConfig={[
          {
            name: 'tinyClassIds',
            label: '款式分类',
            type: 'Cascader',
            option: classIdOptions,
            placeholder: '请选择款式分类',
            config: {
              changeOnSelect: true,
              fieldNames: { label: 'className', value: 'className', children: 'childrenList' },
            },
          },
          {
            label: '是否维护起订量',
            name: 'shopSkcConfigFlag',
            type: 'Select',
            option: [
              { label: '是', value: 1 },
              { label: '否', value: 0 },
            ],
          },
        ]}
        onFinish={(vals: any) => {
          console.log(vals, 'vals')
          const paramsData = {
            ...vals,
            largeClassName: vals?.tinyClassIds?.length > 0 ? vals?.tinyClassIds[0] : null,
            midClassName: vals?.tinyClassIds?.length > 1 ? vals?.tinyClassIds[1] : null,
            smallClassName: vals?.tinyClassIds?.length > 2 ? vals?.tinyClassIds[2] : null,
            tinyClassName: vals?.tinyClassIds?.length > 3 ? vals?.tinyClassIds[3] : null,
          }
          const { tinyClassIds, ...newParams } = paramsData
          search(newParams)
        }}
        onReset={() => {
          reset()
        }}
        extra={
          <div className="table_extra_flex_wrapbox">
            <div className="table_extra_flex">
              <PermissionButton
                icon={<ImportOutlined />}
                permission="displayBatchImport"
                onClick={() => setisUploadFileShow(true)}
              >
                批量导入配置
              </PermissionButton>
            </div>
            <div className="table_extra_flex">
              <PermissionButton
                permission="displayExport"
                icon={<UploadOutlined />}
                loading={exportLoading}
                onClick={async () => {
                  setexportLoading(true)
                  setspinning(true)
                  const res = await displayConfigExportExcel(params)
                    .catch(() => setspinning(false))
                    .finally(() => {
                      setexportLoading(false)
                    })
                  if (res?.code === 200 && res?.data) {
                    await exportNotification(res?.data, navigate).finally(() => setspinning(false))
                  }
                }}
              >
                导出
              </PermissionButton>
            </div>
          </div>
        }
      ></SearchForm>
      <CustomTable
        className="small_sise_customtable"
        bordered
        columns={useDisplayColumns({
          tableData,
          settableData,
          onSave,
          reLoadPage,
          canEdit: buttonCodeList?.includes('displayBatchImport'),
        })}
        {...tableProps}
        rowKey={(rows) => rows.id}
        extraHeight={100}
        isScrollY
        filterDomClassName={'reorder_display'}
      />
      <ImportFileModal
        loading={exportLoading}
        open={isUploadFileShow}
        onCancel={onUploadFileCancel}
        onOk={onUploadFileOk}
        form={FormUpload}
        tempCode={IMPORT_FILE_ENUM.REORDER_DISPLAY_IMPORT}
      ></ImportFileModal>
    </PageContainer>
  )
}

export default Index
